<template>
  <div class="devices">
    <!-- 查询区域 -->
    <div class="search-top-container">
      <Form layout="inline" class="filter-forms">
        <Form.Item label="设备位置">
          <a-cascader
            v-model:value="locationTreeKeys"
            style="width: 308px"
            :options="locationTree"
            placeholder="请选择"
            :field-names="{
              label: 'name',
              value: 'id'
            }"
            multiple
            max-tag-count="responsive"
            :disabled="state !== 0"
            :display-render="({ labels }) => labels.join('/')"
            :show-arrow="true"
            @change="onLocationIdsChange"
          >
            <template #suffixIcon><img src="../../assets/images/tab_icon_dow.png" /></template>
          </a-cascader>
        </Form.Item>
        <Form.Item label="所属班级">
          <a-cascader
            v-model:value="selectDormitoryRoomValue"
            style="width: 308px"
            :options="classData"
            placeholder="请选择"
            multiple
            max-tag-count="responsive"
            :disabled="state !== 0"
            :display-render="({ labels }) => labels.join('/')"
            :show-arrow="true"
            @change="onClassIdsChange"
          >
            <template #suffixIcon><img src="../../assets/images/tab_icon_dow.png" /></template>
          </a-cascader>
        </Form.Item>
        <Form.Item style="margin-right: 0" label="设备状态">
          <a-select
            v-model:value="formDevices.infoState"
            :allow-clear="formDevices.infoState !== ''"
            style="width: 110px"
            :options="infoStateOption"
            :disabled="state !== 0"
            @change="onStateChange"
          >
            <template #suffixIcon><img src="../../assets/images/tab_icon_dow.png" /></template>
            <a-select-option value="">全部</a-select-option>
          </a-select>
        </Form.Item>
      </Form>
    </div>
    <div class="bottom-container">
      <Form class="filter-forms" layout="inline">
        <!-- <Form.Item label="设备名称">
          <a-input
            v-model:value="equipmentName"
            placeholder="请输入设备名称"
            :disabled="state !== 0"
          ></a-input>
        </Form.Item> -->
        <Form.Item>
          <a-input
            v-model:value="controllerUserName"
            style="width: 280px"
            :disabled="state !== 0"
            placeholder="请输入使用者、设备名称"
            @pressEnter="searchDevice"
          >
            <template #prefix>
              <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i>
            </template>
          </a-input>
        </Form.Item>
        <div class="btns">
          <div class="search-btn">
            <a-button type="primary" :disabled="state !== 0" @click="searchDevice">查询</a-button>
            <a-button :disabled="state !== 0" class="gray-btn ml-2" @click="resetForm">
              重置
            </a-button>
          </div>
          <div class="other-btns">
            <template v-if="state === 0">
              <!-- 管理员 -->
              <a-button class="gray-btn mr-2" @click="onSwitch(0)">排序</a-button>
              <a-button
                v-if="store.state.user.identity === 8"
                type="primary"
                @click="authorityManagement"
              >
                权限管理
              </a-button>
            </template>
            <template v-else>
              <a-button class="gray-btn mr-2" @click="onSwitch(1)">取消</a-button>
              <a-button type="primary" @click="KeepSorting">保存排序</a-button>
            </template>
          </div>
        </div>
      </Form>
      <!-- 权限管理弹窗 -->
      <my-dialog
        :dialog-state="power.visible"
        :dialog-title="power.title"
        :dialog-width="power.width"
        :but-status="power.status"
        :btn-state="power.btnState"
        :icon-type="power.iconType"
        @handleCancel="dialogCancel"
        @handleOk="dialogOk"
      >
        <template v-slot:location>
          <div class="power-manage">
            <div class="left">
              <span class="font-color">选择</span>
              <div class="public">
                <div v-if="!isSearch" class="nav white-bg">
                  <div>
                    <template v-for="(item, index) of deptName" :key="index">
                      <span v-if="index !== 0" class="step">></span>
                      <span :class="index === deptName.length - 1 ? 'step-color' : null">
                        <a @click.stop="depList(item, index + 1)">{{ item.deptName }}</a>
                      </span>
                    </template>
                  </div>
                </div>
                <div class="white-bg search">
                  <a-input
                    v-model:value="userName"
                    size="large"
                    placeholder="请输入成员姓名搜索"
                    :maxlength="30"
                    @change="onSearch()"
                    @keyup.enter="onSearch()"
                  >
                    <template #prefix>
                      <!-- <i class="ifont-wid-icon_search" style="color: #c2c2c2"></i> -->
                      <i class="ifont-wid-checkbox_icon_search" @click="onSearch()"></i>
                    </template>
                  </a-input>
                </div>
                <div class="white-bg no-bottom" style="height: 252px; overflow-y: auto">
                  <a-checkbox
                    v-if="!isSearch"
                    v-model:checked="deptStructure.isTrue"
                    style="padding: 12px 0 0 24px; color: #999999"
                    @change.stop="onCheckAllChange"
                  >
                    全选
                  </a-checkbox>
                  <a-checkbox-group v-model:value="selectStudentValue" class="check">
                    <a-menu
                      v-model:openKeys="openStudentValue"
                      v-model:selectedKeys="selectStudentValue"
                      style="width: 280px; padding-left: 0px"
                      mode="inline"
                      :selectable="false"
                    >
                      <a-sub-menu
                        v-for="item of deptStructure.children"
                        :key="item.id"
                        v-model:checked="item.isTrue"
                        :disabled="item.isTrue"
                        @click.stop="item.isTrue == true ? stop : onDeptName(item, item.children)"
                      >
                        <template v-slot:title>
                          <a-checkbox
                            v-model:checked="item.isTrue"
                            :value="item.id"
                            :indeterminate="indeterminate"
                            @click.stop="onDeptNameChecked($event, item, item.deptPersonChildren)"
                          />
                          <span style="margin-left: 10px"> {{ item.deptName }}</span>
                          <i class="ifont-wid-Calendar_icon_month_right" />
                        </template>
                      </a-sub-menu>
                      <a-menu-item v-for="it of deptStructure.deptPersonChildren" :key="it.userId">
                        <a-checkbox
                          v-model:checked="it.isTrue"
                          class="first-all"
                          :value="it.userId"
                          @click.stop="onRealNameChecked($event, it)"
                        >
                          <div class="select-all">
                            <div class="head-portrait">
                              <img v-if="it.avatar" :src="it.avatar" alt="" />
                              <img v-else src="../../assets/images/user_pic_profile.png" alt="" />
                            </div>
                            <div style="font-size: 14px; margin-right: 10px; color: #999999">
                              {{ it.realName }}
                            </div>
                            <span v-if="isSearch" style="font-size: 12px; color: #999999">
                              {{ it.deptName }}
                            </span>
                          </div>
                        </a-checkbox>
                      </a-menu-item>
                    </a-menu>
                  </a-checkbox-group>
                </div>
              </div>
            </div>
            <div class="right">
              <span class="font-color">可用设备列表</span>
              <div class="public">
                <div class="u-felx">
                  <div class="tabs-box">
                    <template v-for="item in deviceTypeTabs" :key="item.id">
                      <div
                        class="tabs-name"
                        :class="[item.id === activeKeys ? 'tab-active' : null]"
                        @click="changeTabs(item)"
                      >
                        {{ item.name }}
                      </div>
                    </template>
                  </div>
                  <div v-if="activeKeys * 1 === 1">
                    <a-button class="power-btn" @click="onRemove()">移除权限</a-button>
                    <a-button
                      type="primary"
                      style="margin-left: 14px"
                      class="btn add-btsn"
                      @click="onAdd"
                    >
                      增加权限
                    </a-button>
                  </div>
                </div>
                <div v-if="activeKeys * 1 === 2" class="equipment-box">
                  <div class="quan-box">
                    <div class="quan-top">
                      <i class="ifont-wid-equipment_icon_dapin" style="margin-top: 3px"></i>
                      <!-- <img class="icon-img" src="../../assets/images/icon_class.png" alt="" /> -->
                      <div>泉城e学</div>
                    </div>
                    <div class="quan-bottom">
                      <a-checkbox v-model:checked="quanCheked" @click="quanchengClick()" />
                      <div class="quan-name">通知公告</div>
                    </div>
                  </div>
                </div>
                <div v-if="activeKeys * 1 === 1" class="equipment-box">
                  <template v-if="rightDeviceList.length !== 0">
                    <div v-for="(ites, index) in rightDeviceList" :key="ites.id">
                      <div class="user-name">{{ ites.realName }}</div>
                      <div v-for="item in ites.availableList" :key="item.id">
                        <template v-if="item.deviceTypeId * 1 !== 999">
                          <Collapse v-model="activeKey" :default-active-key="1">
                            <template v-slot:expandIcon>
                              <i class="ifont-wid-equipment_icon_dapin"></i>
                            </template>
                            <Collapse.Panel key="1" :header="item.positionType">
                              <template #extra>
                                <i class="ifont-wid-card_icon_ktjc" @click.stop="onModify(index)" />
                              </template>
                              <div v-for="items in item.releaseInfoPositionVOS" :key="items.id">
                                <div class="class-content">
                                  <div class="class-title">
                                    <a-checkbox
                                      v-model:checked="items.isTrue"
                                      @click="onEquipments($event, items)"
                                    />
                                    <div
                                      class="nowrap"
                                      style="margin-left: 8px"
                                      :title="items.deviceName"
                                    >
                                      {{ items.deviceName }}
                                    </div>
                                    <div class="nowrap" :title="items.clazzName">
                                      {{ items.clazzName }}
                                    </div>
                                    <div :title="items.locationName" class="nowrap">
                                      {{ items.locationName }}
                                    </div>
                                    <div class="right">
                                      <i
                                        class="ifont-wid-equipment_icon_del"
                                        @click="removeOne(items, ites)"
                                      ></i>
                                    </div>
                                  </div>
                                  <div class="content class-card">
                                    <div
                                      v-for="ite in items.funcModules"
                                      :key="ite.equipmentId"
                                      class="data-btn"
                                    >
                                      <span>{{ ite.funcModuleName }}</span>
                                    </div>
                                  </div>
                                </div>
                              </div>
                            </Collapse.Panel>
                          </Collapse>
                        </template>
                      </div>
                    </div>
                  </template>
                  <Empty v-else class="shebei" :image="simpleImage" style="padding-top: 30px" />
                </div>
              </div>
            </div>
          </div>
        </template>
      </my-dialog>
      <!-- 增加设备弹窗 -->
      <my-dialog
        :dialog-state="addDevice.visible"
        :dialog-title="addDevice.title"
        :dialog-width="addDevice.width"
        :icon-type="addDevice.iconType"
        @handleCancel="addCancel"
        @handleOk="addOk"
      >
        <template v-slot:location>
          <div class="power-manage">
            <div class="left-device">
              <span class="font-color">选择</span>
              <div class="public" style="height: 480px; overflow-y: auto">
                <div class="white-bg search">
                  <a-input
                    v-model:value="equipmentName"
                    size="large"
                    placeholder="请输入搜索设备"
                    :maxlength="30"
                    @keyup.enter="onEquipmentSearch"
                    @change="onEquipmentSearch"
                  >
                    <template #prefix>
                      <i class="ifont-wid-checkbox_icon_search"></i>
                    </template>
                  </a-input>
                </div>
                <div v-for="(item, index) in selectionList" :key="item.id">
                  <Collapse
                    v-model:activeKey="activeKey"
                    :default-active-key="item.id"
                    :collapsible="disabled"
                    :show-arrow="true"
                    @change="change"
                  >
                    <template v-slot:expandIcon>
                      <div class="collapse-expand-icons">
                        <a-checkbox
                          v-model:checked="item.isTrue"
                          style="margin-right: 10px; color: #999999"
                          @change="onSelectAll($event, item, item.releaseInfoPositionVOS, index)"
                          @click.stop
                        >
                        </a-checkbox>
                        <i class="ifont-wid-equipment_icon_dapin"></i>
                        <i class="ifont-wid-equipment_icon_lower"></i>
                        <!-- <i v-if="!dropDown" class="ifont-wid-equipment_icon_lower"></i>
                    <i v-if="dropDown" class="ifont-wid-equipment_icon_upper"></i> -->
                      </div>
                    </template>
                    <Collapse.Panel :key="index" :header="item.positionType">
                      <div
                        v-for="items in item.releaseInfoPositionVOS"
                        :key="items.deviceId"
                        :class="{ active: item.isTrue === true }"
                        class="checkbox-device"
                      >
                        <a-checkbox
                          v-model:checked="items.isTrue"
                          @click="onEquipment($event, items, item)"
                        >
                          <div style="display: flex">
                            <div class="checkbox-spacing" :title="items.deviceName">
                              {{ items.deviceName }}
                            </div>
                            <div class="name" :title="items.locationName">
                              {{ items.locationName }}
                            </div>
                            <div class="title" :title="items.clazzName">
                              {{ items.clazzName }}
                            </div>
                          </div>
                        </a-checkbox>
                      </div>
                    </Collapse.Panel>
                  </Collapse>
                </div>
                <Empty
                  v-if="selectionList.length === 0"
                  style="padding-top: 21px"
                  :image="simpleImage"
                />
              </div>
              <span> 已选：{{ selectLength }} </span>
            </div>
            <div class="right">
              <span class="font-color">已选</span>
              <div class="public" style="height: 480px; overflow-y: auto">
                <div v-if="selectedOptions.length !== 0" class="class-box">
                  <div class="all-checked">
                    <tj-checkbox
                      :checked="selectedCheckAll"
                      :indeterminate="selectedIndeterminate"
                      :on-change="selectedHandleSelectAll"
                      >全选</tj-checkbox
                    >
                  </div>
                  <tj-checkbox-group
                    v-model="selectedValue"
                    :options="selectedOptions"
                    @change="selectedOnChange"
                    @click="selectedOnClick"
                  />
                </div>
                <Empty
                  v-if="selectDevice.length === 0"
                  style="padding-top: 73px"
                  :image="simpleImage"
                />
                <template v-else>
                  <div v-for="(item, index) in selectDevice" :key="item.id">
                    <Collapse v-model="activeKey" :default-active-key="1">
                      <template v-slot:expandIcon>
                        <i class="ifont-wid-equipment_icon_dapin"></i>
                        <i class="ifont-wid-Upload_icon_dete" @click.stop="onDelete(index)"></i>
                      </template>
                      <Collapse.Panel key="1" :header="item.positionType">
                        <template v-for="items in item.releaseInfoPositionVOS" :key="items.id">
                          <div class="class-titles">
                            <div class="nowrap" :title="items.deviceName">
                              {{ items.deviceName }}
                            </div>

                            <div class="nowrap nowrap-icon" :title="items.locationName">
                              <img
                                class="icon-img"
                                src="../../assets/images/icon_location.png"
                                alt=""
                              />
                              {{ items.locationName || '--' }}
                            </div>
                            <div class="nowrap nowrap-icon" :title="items.clazzName">
                              <img
                                class="icon-img"
                                src="../../assets/images/icon_class.png"
                                alt=""
                              />
                              {{ items.clazzName || '--' }}
                            </div>
                            <div class="right">
                              <i class="ifont-wid-equipment_icon_del" @click="onDele(items)"></i>
                            </div>
                          </div>
                          <div class="content-device">
                            <div
                              v-for="(elme, indexs) in items.funcModules"
                              :key="elme.id"
                              class="check-box"
                            >
                              <a-checkbox
                                v-if="elme.funcModule === '111'"
                                class="moudel-all"
                                :checked="elme.isTrue"
                                :indeterminate="elme.indeterminate"
                                @click="moudelSelectAll($event, items.funcModules, indexs)"
                                >全选</a-checkbox
                              >
                              <a-checkbox
                                v-else
                                v-model:checked="elme.isTrue"
                                @click="onSelected($event, elme, index, '模块', items.funcModules)"
                              >
                                {{ elme.funcModuleName }}
                              </a-checkbox>
                            </div>
                          </div>
                        </template>
                      </Collapse.Panel>
                    </Collapse>
                  </div>
                </template>
              </div>
            </div>
          </div>
        </template>
      </my-dialog>
      <!-- 修改弹窗-->
      <my-dialog
        :dialog-state="modify.visible"
        :dialog-title="modify.title"
        :dialog-width="modify.width"
        :but-status="modify.status"
        :icon-type="modify.iconType"
        @handleCancel="modifyCancel"
        @handleOk="modifyOk"
      >
        <template v-slot:location>
          <div style="height: 480px; overflow-y: auto">
            <div v-for="item in editList.availableList" :key="item.id" class="modify">
              <Collapse v-model="activeKey" :default-active-key="1">
                <template v-slot:expandIcon>
                  <i class="ifont-wid-equipment_icon_dapin"></i>
                </template>
                <Collapse.Panel key="1" :header="item.positionType">
                  <template v-for="items in item.releaseInfoPositionVOS" :key="items.id">
                    <div v-if="items.funcModules.length !== 0" class="class-title">
                      <div class="nowrap" :title="items.deviceName">
                        {{ items.deviceName }}
                      </div>
                      <div class="modify-right nowrap" :title="items.locationName">
                        {{ items.locationName }}
                      </div>
                      <div class="nowrap" style="color: #666666" :title="items.clazzName">
                        {{ items.clazzName }}
                      </div>
                    </div>
                    <div class="content-device">
                      <div v-for="elme in items.funcModules" :key="elme.id" class="check-box">
                        <a-checkbox
                          v-model:checked="elme.isTrue"
                          @click="onSelected($event, elme, index)"
                        >
                          <span>{{ elme.funcModuleName }}</span>
                        </a-checkbox>
                      </div>
                    </div>
                  </template>
                </Collapse.Panel>
              </Collapse>
            </div>
          </div>
        </template>
      </my-dialog>
      <!-- 移除设备 -->
      <my-dialog
        :dialog-state="remove.visible"
        :dialog-title="remove.title"
        :dialog-width="remove.width"
        :icon-type="remove.warring"
        :show-icon="true"
        :draft-box-visible="false"
        :content-text="remove.content"
        @handleCancel="removeCancel"
        @handleOk="removeOk"
      ></my-dialog>
      <!-- 二次移除提示框 -->
      <my-dialog
        :dialog-state="removes.visible"
        :dialog-title="removes.title"
        :dialog-width="removes.width"
        :icon-type="removes.warring"
        :show-icon="true"
        :draft-box-visible="false"
        :content-text="removes.content"
        @handleCancel="removeCancels"
        @handleOk="removeOks"
      ></my-dialog>
      <!-- 设备列表组件 -->
      <!-- {{ modelList }} -->
      <div class="list-box">
        <Deviceslist v-if="state === 0" ref="deviceslist" :devices-list="modelList"></Deviceslist>
        <!-- 设备列表_排序组件-->
        <Sortlist
          v-else
          ref="childRefSortlist"
          :sort-list="modelList"
          @SortlistData="getSortlistData"
          @unsortData="unsortData"
        ></Sortlist>
        <!-- <Empty v-if="modelList.length === 0" class="no-list" :image="simpleImage" /> -->
      </div>
    </div>
  </div>
</template>
<script>
export default {
  name: 'Devices'
};
</script>
<script setup>
import { Form, Row, Col, Breadcrumb, Collapse, Empty, Message, Menu } from 'ant-design-vue';
import {
  onMounted,
  reactive,
  ref,
  computed,
  watch,
  nextTick,
  defineEmits,
  onActivated,
  onDeactivated
} from 'vue';
import { DownOutlined } from '@ant-design/icons-vue';
import MyDialog from '@/components/dialog/index.vue';
import Deviceslist from './list/devices-list.vue';
import Sortlist from './sort/sort-list.vue';
import {
  saveEquipment,
  availableEquipment,
  getAllDeptInfo,
  getDeviceListEast,
  getLocationList,
  getClassTree,
  getDeviceListCompetence,
  saveEquipmentSort,
  saveEquipments
} from '@/api/user';
import { useStore } from 'vuex';

const selectedOptions = ref([]); // 所有的模块类型（不同的）
const selectedValue = ref([]); // 已选设备 默认选中值id['111'，'222']
const selectedValueDefault = ref([]); // 已选设备 默认选中值id['111'，'222'] 存储一下
const selectedCheckAll = computed(
  () => selectedOptions.value.length === selectedValue.value.length
); // 全选状态
const selectedIndeterminate = computed(
  // 全选半全选状态
  () => !!(selectedOptions.value.length > selectedValue.value.length && selectedValue.value.length)
);
const selectedHandleSelectAll = checked => {
  selectedValue.value = checked ? selectedValueDefault.value : [];
  allmoudelClick(null, checked);
};
// 多选click事件
function selectedOnClick(val) {
  // allmoudelClick(val, 'click');
}
// 右侧已选功能模块的全选事件
function moudelSelectAll(val, elme, index) {
  elme[index].isTrue = val.target.checked;
  elme.forEach(item => {
    if (item.funcModule !== '111') item.isTrue = val.target.checked;
    if (!val.target.checked) {
      // 取消选中
      selectedValue.value = selectedValue.value.filter(i => i !== item.funcModule);
    }
    if (val.target.checked) {
      aa(item.funcModule);
    }
  });
  selectedValue.value = [...new Set(selectedValue.value || [])];
  // console.log('选中的所有集合', selectedValue.value);
  // console.log(selectedOptions.value.length);
}
function aa(id) {
  // 选中全选
  let allList = []; // 当前模块所有id集合
  let list = []; // 当前模块选中状态下有id集合
  selectDevice.value.forEach(items => {
    items.releaseInfoPositionVOS.forEach(it => {
      it.funcModules.forEach(i => {
        if (i.funcModule === id) {
          allList.push(i.funcModule);
          if (i.isTrue) {
            list.push(i.funcModule);
          }
        }
      });
    });
  });
  if (list.length === allList.length) {
    if (id !== '111') selectedValue.value.push(id);
  }
}
function allmoudelClick(val, checked, state) {
  selectDevice.value.forEach(item => {
    item.releaseInfoPositionVOS.forEach(it => {
      getSelectDeviceChild(it.funcModules, val, checked, state);
    });
  });
  // 改变已选模块的全选状态（拿到所有已选设备的模块， 除去全选’111‘， 根据选中的数量跟全部的数量判断istrue的状态）
  selectDevice.value.forEach(item => {
    item.releaseInfoPositionVOS.forEach(it => {
      let allList = []; // 模块所有状态集合
      let list = []; // 模块选中状态下有状态集合
      it.funcModules.forEach(i => {
        if (i.funcModule !== '111') {
          allList.push(i.isTrue);
          if (i.isTrue) {
            list.push(i.isTrue);
          }
        }
      });
      if (list.length === 0) {
        it.funcModules[0].isTrue = false;
        it.funcModules[0].indeterminate = false;
      } else if (list.length === allList.length) {
        it.funcModules[0].isTrue = true;
        it.funcModules[0].indeterminate = false;
      } else {
        it.funcModules[0].isTrue = false;
        it.funcModules[0].indeterminate = true;
      }
    });
  });
}
// 多选change事件
const selectedOnChange = (val, eve) => {
  // console.log(eve);
  selectedValue.value = val;
  allmoudelClick(eve.current, 'click', eve.option.checked || false);
};
function getSelectDeviceChild(data, val, checked, state) {
  // console.log('点击data', val, checked, state);
  let checkedList = []; // 所有模块的选中状态除去全选
  data.forEach(item => {
    if (checked === 'click') {
      if (val * 1 === item.funcModule * 1) {
        item.isTrue = !state;
      }
    } else {
      item.isTrue = checked;
    }
    if (item.funcModule !== '111') checkedList.push(item.isTrue);
  });
  // console.log(checkedList);
}
let deviceTypeTabs = ref([
  { name: '设备', id: 1 },
  { name: '应用', id: 2 }
]);
let activeKeys = ref(2); // 可选设备的选中涨停
function changeTabs(item) {
  // console.log(selectStudentValue.value);
  // if (selectStudentValue.value.length === 0) {
  //   Message.warning('请先选择成员！');
  //   return;
  // }
  activeKeys.value = item.id;
}
let quanCheked = ref(false); // 通知公告选中状态
const store = useStore();
let equipmentName = ref(''); // 设备名称
let controllerUserName = ref(''); // 使用者名称
const rightDeviceList = ref([]); // 可以设备集合
// 设备类型接口;
const modelList = ref([]);

// 页面被激活时
const isFirstLoadPage = ref(true);
onActivated(() => {
  // console.log('onActivated');
  if (!isFirstLoadPage.value) {
    getData();
  }
});
onDeactivated(() => {
  isFirstLoadPage.value = false;
});

onMounted(() => {
  getData(); // 获取设备数据
  getLocation(); // 获取位置信息
  getClass(); // 获取班级
});
/** *********************************弹窗数据区**************************************** **/
// 权限管理弹窗
const power = reactive({
  title: '权限管理',
  visible: false,
  btnState: '保存',
  status: '保存',
  width: '916px',
  iconType: 'default'
});
// 修改弹窗
const modify = reactive({
  title: '修改',
  visible: false,
  status: '保存',
  width: '546px',
  iconType: 'default'
});
// 增加设备弹窗addDevice
const addDevice = reactive({
  title: '选择设备',
  visible: false,
  width: '1158px',
  iconType: 'default'
});
// 弹窗相关
const dialog = reactive({
  title: '所在位置',
  iconType: 'default',
  visible: false,
  width: '392px'
});
const dialogClass = reactive({
  title: '所属班级',
  iconType: 'default',
  visible: false,
  width: '385px'
});
// 移除设备
const remove = reactive({
  type: 'recall',
  title: '温馨提示',
  content: '是否将所选权限从当前管理员权限列表中移除？',
  warring: 'warring',
  visible: false,
  width: '330px'
});
const removes = reactive({
  type: 'recall',
  title: '温馨提示',
  content: '此操作将会取消当前所做设置，是否确认继续 ？',
  warring: 'warring',
  visible: false,
  width: '330px'
});
// 移除设备提示框
function onRemove() {
  if (rightDeviceList.value.length === 0) {
    Message.warning('请至少选择一条移除的数据');
    return;
  }
  let availableList = [];
  rightDeviceList.value.forEach(el => {
    availableList.push(...el.availableList);
  });
  let checkedData = [];
  // console.log(availableList);
  availableList.forEach(item => {
    if (item.releaseInfoPositionVOS) {
      item.releaseInfoPositionVOS.forEach(elme => {
        checkedData.push(elme.isTrue);
      });
    }

    // 如果不存在true就提示
  });
  if (checkedData.indexOf(true) === -1) {
    Message.warning('请至少选择一条移除的数据');
  } else {
    remove.visible = true;
  }
}

/** *********************************数据区域**************************************** **/
const openDormitoryRoomValue = ref([]);
const selectDormitoryRoomValue = ref([]);
const simpleImage = ref(require('@/assets/images/noData@2x.png'));
let selectedKeys = ref([]); // 当前被点击的节点
let selectionList = ref([]); // 选择列表
const current = ref(1);
const choiceClass = ref(''); // 筛选班级value
const locationChoice = ref(''); // 位置选中数据
let selectDevice = ref([]); // 可选设备
const disabled = ref(false);
const locationTreeKeys = ref([]);
let locationexpandedKeys = ref([]);
const locationTree = ref([]); // 位置信息
const formRef = ref();
const state = ref(0);
let addModelList = ref([]); // 增加设备列表
const activeKey = ref([]);
const indeterminate = ref(false);
const classData = ref([]); // 班级数据
// 表单数据
const formDevices = reactive({
  infoState: ''
});
// 设备状态
const infoStateOption = reactive([
  {
    value: '',
    label: '全部'
  },
  {
    value: 0,
    label: '离线'
  },
  {
    value: 1,
    label: '在线'
  }
]);

/** *********************************方法区域**************************************** **/
function onClassData(item) {
  classData.value.forEach(elem => {
    elem.classList.forEach(x => {
      if (x.classId === item.key) {
        choiceClass.value = x.className;
      }
    });
  });
  classId.value = item.key;
}
function onExpand(expandedKeys) {
  expandedKeys.value = expandedKeys;
}
// 点击树节点触发
let classId = ref(''); // 班级id
function onSelectClass(selectedKeys, info, event) {
  choiceClass.value = info.node.title;
  classId.value = selectedKeys.join(',');
}
// 获取班级结构
function getClass() {
  getClassTree().then(res => {
    classData.value = res.data.data.map(s => {
      let section = {
        value: s.sectionCode,
        label: s.sectionName
      };
      if (s.children?.length > 0) {
        section.children = getGradeAndClassTree(s.children);
      }
      return section;
    });
  });
}
// 处理年级班级树
function getGradeAndClassTree(gradeList) {
  return gradeList.map(g => {
    let grade = {
      value: g.businessId,
      label: `${g.schoolYear}级`
    };
    if (g.children?.length > 0) {
      grade.children = g.children.map(c => ({ value: c.businessId, label: c.className }));
    }
    return grade;
  });
}

function dialogPosition() {
  dialog.visible = false;
  locationId.value = ''; // 清空位置id
  locationTreeKeys.value = [];
  locationChoice.value = '';
}
function positionOk() {
  dialog.visible = false;
}
function onClass() {
  choiceClass.value = '';
  classId.value = ''; // 清空班级id
  selectedKeys.value = []; // 清空选中
  dialogClass.visible = false;
}
function classOk() {
  dialogClass.visible = false;
}
// 获取位置信息
function getLocation() {
  getLocationList().then(res => {
    if (res.data.data !== undefined) {
      locationTree.value = res.data.data[0].children ? res.data.data[0].children : [];
    }
  });
}

// 设备搜索
function onEquipmentSearch() {
  onAddDevice();
}
// 选择设备-已选事件
function onSelected(e, data, index, type, allData) {
  // type=’模块‘ 为了不改变原来逻辑 区分已选 模块的选中事件; allData=整个模块数组；data当前点击的模块
  data.isTrue = e.target.checked;
  if (type === '模块') {
    let checkedState = []; // 当前所有模块选中的状态集合
    allData.forEach(item => {
      if (item.funcModule !== '111' && item.isTrue) checkedState.push(item.isTrue);
    });
    // console.log(checkedState.length, allData.length - 1);
    if (checkedState.length === 0) {
      allData[0].indeterminate = false; // 第0个事全选
      allData[0].isTrue = false; // 第0个事全选
    } else if (checkedState.length === allData.length - 1) {
      allData[0].indeterminate = false; // 第0个事全选
      allData[0].isTrue = true; // 第0个事全选
    } else {
      allData[0].indeterminate = true; // 第0个事全选
      allData[0].isTrue = false; // 第0个事全选
    }
    // 改变顶部类型模块状态(拿到所选中设备下的所有模块， 如果跟当前处理的相同， 通过判断选中的模块数量跟全部数量比较， 处理selectedValue数组)
    let allList = []; // 当前模块所有id集合
    let list = []; // 当前模块选中状态下有id集合
    selectDevice.value.forEach(item => {
      item.releaseInfoPositionVOS.forEach(it => {
        it.funcModules.forEach(i => {
          if (i.funcModule === data.funcModule) {
            allList.push(i.funcModule);
            if (i.isTrue) {
              list.push(i.funcModule);
            }
          }
        });
      });
    });
    if (list.length !== allList.length) {
      selectedValue.value = selectedValue.value.filter(item => item !== data.funcModule);
    } else {
      selectedValue.value.push(data.funcModule);
    }
  }
}
function selectedClose() {
  selectDeviceId.value = []; // 清空已选中的id
  selectModelId.value = []; // 清空已选中的id
  equipmentName.value = '';
  selectedOptions.value = []; // 所有的模块类型（不同的）
  selectedValue.value = []; // 已选设备 默认选中值id['111'，'222']
  selectedValueDefault.value = [];
  selectDevice.value = []; // 清空可选数据
}
// 选择设备-确定事件
function addOk() {
  if (selectDevice.value.length) {
    let availableList2 = [];
    selectDevice.value.forEach(item => {
      let releaseInfoPositionVOS = [];
      item.releaseInfoPositionVOS.forEach(elme => {
        let funcModules = [];
        elme.funcModules.forEach(el => {
          if (el.isTrue) {
            funcModules.push({
              configIds: el.configIds,
              isTrue: el.isTrue,
              funcModule: el.funcModule,
              equipmentId: el.equipmentId,
              funcModuleName: el.funcModuleName
            });
          }
        });
        let arrTrue = elme.funcModules.map(elmes => {
          return elmes.isTrue;
        });
        // 包含true就执行
        if (arrTrue.indexOf(true) !== -1) {
          releaseInfoPositionVOS.push({
            isTrue: false,
            clazzId: elme.clazzId,
            clazzName: elme.clazzName,
            deviceId: elme.deviceId,
            deviceName: elme.deviceName,
            locationId: elme.locationId,
            locationName: elme.locationName,
            modelId: elme.modelId,
            modelName: elme.modelName,
            onlineStatus: elme.onlineStatus,
            funcModules: funcModules
          });
        }
      });
      availableList2.push({
        // deviceId: item.deviceId,
        deviceTypeId: item.deviceTypeId,
        modelId: item.modelId,
        positionType: item.positionType,
        releaseInfoPositionVOS: releaseInfoPositionVOS
      });
      availableList2.forEach(elem => {
        if (elem.releaseInfoPositionVOS.length === 0) {
          Message.warning('请选择功能模块');
        } else {
          addDevice.visible = false;
          power.visible = true;
          selectDevice.value = []; // 清空可选数据
        }
      });
    });

    availableList2.forEach(v => {
      rightDeviceList.value.forEach(x => {
        let userAvailableList = x.availableList.filter(
          item => item.deviceTypeId === v.deviceTypeId
        );
        // 本身没有设备
        if (!userAvailableList.length) {
          x.availableList.push(v);
        } else {
          // 勾选人有设备
          v.releaseInfoPositionVOS.forEach(info => {
            let releaseInfo = userAvailableList[0].releaseInfoPositionVOS.filter(
              // eslint-disable-next-line max-nested-callbacks
              item => item.deviceId === info.deviceId
            );
            if (!releaseInfo.length) {
              userAvailableList[0].releaseInfoPositionVOS.push(info);
            } else {
              // eslint-disable-next-line max-nested-callbacks
              info.funcModules.forEach(value => {
                let fun = releaseInfo[0].funcModules.filter(
                  // eslint-disable-next-line max-nested-callbacks
                  item => item.funcModule === value.funcModule
                );
                if (!fun.length) {
                  releaseInfo[0].funcModules.push(value);
                }
              });
            }
          });
        }
      });
    });
  } else {
    addDevice.visible = false;
    power.visible = true;
  }
  onEquipmentSearch();
  selectedClose(); // 清除已选择弹窗内容
  // console.log(rightDeviceList.value, 7787878);
}
function uniqueArray(array, key) {
  let result = [array[0]];
  for (let i = 1; i < array.length; i++) {
    let item = array[i];
    let repeat = false;
    for (let j = 0; j < result.length; j++) {
      if (item[key] === result[j][key]) {
        repeat = true;
        break;
      }
    }
    if (!repeat) {
      result.push(item);
    }
  }
  return result;
}
// 修改弹窗 确定事件
function modifyOk() {
  modify.visible = false;
  power.visible = true;
  let availableList = [];
  editList.value.availableList.forEach((item, ind) => {
    let releaseInfoPositionVOS = [];
    item.releaseInfoPositionVOS.forEach((elme, index) => {
      let funcModules = [];
      elme.funcModules.forEach(el => {
        if (el.isTrue) {
          funcModules.push({
            isTrue: el.isTrue,
            configIds: el.configIds,
            funcModule: el.funcModule,
            funcModuleName: el.funcModuleName,
            equipmentId: elme.deviceId
          });
        }
      });
      // 给一个新数组保存多选框状态
      let arrTrue = elme.funcModules.map(elmes => {
        return elmes.isTrue;
      });
      // 包含true就执行
      if (arrTrue.indexOf(true) !== -1) {
        releaseInfoPositionVOS.push({
          isTrue: false,
          clazzId: elme.clazzId,
          clazzName: elme.clazzName,
          deviceId: elme.deviceId,
          deviceName: elme.deviceName,
          locationId: elme.locationId,
          locationName: elme.locationName,
          modelId: elme.modelId,
          modelName: elme.modelName,
          onlineStatus: elme.onlineStatus,
          funcModules: funcModules
        });
      }
    });
    availableList.push({
      deviceTypeId: item.deviceTypeId,
      modelId: item.modelId,
      positionType: item.positionType,
      controllerUserId: item.controllerUserId,
      releaseInfoPositionVOS: releaseInfoPositionVOS
    });
    availableList.forEach((item, index) => {
      if (item.releaseInfoPositionVOS.length === 0) {
        availableList.splice(index, 1);
      }
    });
    rightDeviceList.value[indexs.value].availableList = availableList;
  });
}
let indexs = ref(); // 修改成员下标
// 设备选中事件
function onEquipment(e, data, dataList) {
  // console.log(2222, e.target.checked);
  let all = [
    {
      isTrue: true, // 全选
      indeterminate: false, // 半全选
      funcModule: '111',
      funcModuleName: '全选',
      value: '111',
      label: '全选'
    }
  ];
  if (data.funcModules[0].funcModule !== '111') data.funcModules = [...all, ...data.funcModules];
  selectDeviceId.value = []; // 清空设备id
  // 默认选中功能模块
  data.funcModules.forEach(item => {
    item.isTrue = true;
  });
  data.isTrue = e.target.checked;
  // 全部选中为全选
  selectionList.value.forEach(items => {
    let checkedData = [];
    items.releaseInfoPositionVOS.forEach(elme => {
      checkedData.push(elme.isTrue);
    });
    if (checkedData.indexOf(false) !== -1) {
      items.isTrue = false;
    } else {
      items.isTrue = true;
    }
  });
  // 选中就添加，取消是删除
  if (e.target.checked) {
    let type = selectDevice.value.map(x => x.modelId).indexOf(data.modelId);
    if (type === -1) {
      selectDevice.value.push({
        deviceId: data.deviceId,
        deviceTypeId: dataList.deviceTypeId,
        modelId: data.modelId,
        positionType: data.modelName,
        isTrue: true,
        releaseInfoPositionVOS: []
      });
    }
    selectDevice.value.forEach(elem => {
      elem.modelId === data.modelId && elem.releaseInfoPositionVOS.push(data);
    });
  } else {
    selectDevice.value.forEach((elem, index) => {
      if (elem.modelId === data.modelId) {
        elem.releaseInfoPositionVOS.splice(
          elem.releaseInfoPositionVOS.map(x => x.deviceId).indexOf(data.deviceId),
          1
        );
      }
      if (elem.releaseInfoPositionVOS.length === 0) {
        selectDevice.value.splice(index, 1);
      }
    });
  }
  getSelectDeviceId(); // 选中就增加取消就移除id
  getAllClass(); // 获取所有已选设备的模块类
}
// 选择设备-移除事件
function onDele(data) {
  selectDeviceId.value = []; // 清空设备id
  selectModelId.value = []; // 清空设备类型id
  selectDevice.value.forEach((elem, index) => {
    if (elem.modelId === data.modelId) {
      elem.releaseInfoPositionVOS = elem.releaseInfoPositionVOS.filter(
        v => v.deviceId !== data.deviceId
      );
    }
  });
  selectDevice.value = selectDevice.value.filter(v => v.releaseInfoPositionVOS.length);
  selectionList.value.forEach(item => {
    if (item.modelId === data.modelId) {
      item.releaseInfoPositionVOS.forEach(voElem => {
        if (voElem.deviceId === data.deviceId) {
          item.isTrue = false;
          voElem.isTrue = false;
        }
      });
    }
  });
  getSelectDeviceId(); // 搜索后移除时 清空id
}
// 取消和确定事件
function removeCancels() {
  removes.visible = false;
}
let removeState = ref(true); // 删除的状态 右侧的删除按钮是false
// 二次确定移除
function removeOks() {
  selectDeviceId.value = [];
  selectModelId.value = [];
  if (removeState.value) {
    // 选择的移除
    selectionList.value.forEach((item, index) => {
      // 根据下标控制当前的状态
      if (index === selectIndex.value) {
        item.releaseInfoPositionVOS.forEach(elme => {
          elme.isTrue = false;
        });
        item.isTrue = false;
        selectDevice.value = JSON.parse(
          JSON.stringify(selectDevice.value.filter(v => v.modelId !== item.modelId))
        );
        // JSON.parse(JSON.stringify(datas));
      }
      // 当前为true就push
      // if (item.isTrue) {
      //   datas.push(item);
      // }
    });
  } else {
    selectDevice.value[removeIndex.value].isTrue = false;
    let datas = [];
    selectionList.value.forEach((item, index) => {
      if (item.modelId === selectDevice.value[removeIndex.value].modelId) {
        item.releaseInfoPositionVOS.forEach(items => {
          items.isTrue = false;
        });
        item.isTrue = false;
      }
    });
    selectDevice.value.forEach((item, index) => {
      if (item.isTrue) {
        datas.push(item);
      }
      selectDevice.value = JSON.parse(JSON.stringify(datas));
    });
  }
  removes.visible = false;
  // console.log('已选设备22', selectDevice.value);
  getAllClass(); // 获取所有已选设备的模块类
}
// 获取所有已选设备的模块类 releaseInfoPositionVOS
function getAllClass() {
  let list = []; // 选中的所有模块
  selectDevice.value.forEach(item => {
    item.releaseInfoPositionVOS.forEach(it => {
      it.funcModules.forEach(i => {
        i.value = i.funcModule;
        i.label = i.funcModuleName;
        list.push(i);
      });
    });
  });
  let uniqueArr = list.filter((v, i, a) => a.findIndex(t => t.funcModule === v.funcModule) === i); // 根据funcModule找到并集
  // console.log(uniqueArr);
  uniqueArr = uniqueArr.filter(item => item.funcModule !== '111'); // 去除不等于1111的 全选
  let idList = [];
  uniqueArr.forEach(item => {
    idList.push(item.funcModule);
  });
  selectedOptions.value = uniqueArr;
  selectedValue.value = idList; // 所有选中id
  selectedValueDefault.value = idList; // 所有选中id 暂存
}
let removeIndex = ref();
function onDelete(e) {
  removeState.value = false;
  removeIndex.value = e;
  removes.visible = true;
}
const selectIndex = ref('');
let selectModelId = ref([]); // 设备类型id
let selectDeviceId = ref([]); // 设备id
// 选择设备全选
function onSelectAll(e, data, releaseData, index) {
  console.log(data);
  // console.log(222222, selectionList.value);
  data.releaseInfoPositionVOS.forEach(ite => {
    let all = [
      {
        isTrue: true, // 全选
        indeterminate: false, // 半全选
        funcModule: '111',
        funcModuleName: '全选',
        value: '111',
        label: '全选'
      }
    ];
    if (ite.funcModules[0].funcModule !== '111') ite.funcModules = [...all, ...ite.funcModules];
    // ite.funcModules = ite.funcModules.unshift();
  });
  // console.log(data);
  removeState.value = true;
  selectIndex.value = index;
  data.isTrue = e.target.checked;
  if (e.target.checked) {
    releaseData.forEach(elme => {
      elme.funcModules.forEach(item => {
        item.isTrue = true;
      });

      elme.isTrue = e.target.checked;
    });
    // console.log(releaseData);
    let datas = [];
    selectionList.value.forEach(item => {
      if (item.isTrue) {
        datas.push(item);
      }
    });
    // 解决全选时设备重复的问题
    let oldFormData = selectDevice.value.filter(v => v.modelId === data.modelId);
    if (!oldFormData.length) {
      selectDevice.value = JSON.parse(JSON.stringify([...selectDevice.value, data]));
    } else {
      let ids = oldFormData[0].releaseInfoPositionVOS.map(v => v.deviceId);
      data.releaseInfoPositionVOS.forEach(v => {
        if (ids.indexOf(v.deviceId) === -1) {
          oldFormData[0].releaseInfoPositionVOS.push(v);
        }
      });
    }
  } else {
    data.isTrue = true;
    removes.visible = true;
  }
  getSelectDeviceId(); // 选中就添加id,取消就移除id
  // console.log('已选设备', selectDevice.value);
  getAllClass(); // 获取所有已选设备的模块类
}
// 选中就添加id,取消就移除id
function getSelectDeviceId() {
  selectDevice.value.forEach(x => {
    selectModelId.value.push(x.modelId);
    x.releaseInfoPositionVOS.forEach(v => {
      selectDeviceId.value.push(v.deviceId);
    });
  });
}
// 增加设备点击事件
function onAdd() {
  if (rightDeviceList.value.length === 0) {
    Message.warning('请先选择成员');
    return;
  }
  power.visible = false;
  addDevice.visible = true;
  // 组装数据（增加一个状态）
  let datas = [];
  addModelList.value.forEach(elem => {
    let releaseInfoPositionVOS = [];
    elem.data.forEach(item => {
      // 组装moduleVOList数据
      let funcModules = [];
      if (item.moduleVOList !== undefined) {
        let moduleVOList = [];
        item.moduleVOList.forEach(el => {
          moduleVOList.push({
            isTrue: false,
            configIds: el.configIds,
            funcModule: el.configId,
            equipmentId: item.deviceId,
            funcModuleName: el.configName
          });
        });
        funcModules = moduleVOList;
      }
      releaseInfoPositionVOS.push({
        isTrue: false,
        clazzId: item.clazzId,
        clazzName: item.clazzName,
        deviceId: item.deviceId,
        deviceName: item.deviceName,
        locationId: item.locationId,
        locationName: item.locationName,
        modelId: item.modelId,
        modelName: item.modelName,
        onlineStatus: item.onlineStatus,
        funcModules: funcModules
      });
    });
    datas.push({
      deviceTypeId: elem.deviceTypeId,
      modelId: elem.modelId,
      positionType: elem.name,
      isTrue: false,
      releaseInfoPositionVOS: releaseInfoPositionVOS
    });
  });
  selectionList.value = datas;
}

/** ************************* 组织架构数据结构 ***************************************** */
const userListAll = ref([]); // 当前部门下所有成员
const deptStructure = ref({
  deptPersonChildren: [],
  children: []
}); // 部门结构数据
const userAmount = ref([]); // 总人数
const deptName = ref([]); // 部门面包屑标题
const list = ref([]); // 当前部门选择人员
const selectedCheckedAll = ref(false); // 是否全选
const selectedChecked = ref(false);
const selectStudentValue = ref([]);
// const selectTotal = ref([]); // 已选择的所有人
const isUserAll = ref([]); // 获取部门所有人员
const userName = ref(''); // 全员搜索
const deptStructureCopy = ref({}); // 部门结构数据备份
const isSearch = ref(false); // 是否搜索
// DIds = [];
/** **模糊查询*****/
// 1-1.获取部门所有人员
const getDeptNumTotal = data => {
  isUserAll.value = [];
  isUserAll.value = [...isUserAll.value, ...data.deptPersonChildren];
  // 获取该部门下所有成员
  getisUserAll(data.children);
  let arr = deduplication(isUserAll.value);
  isUserAll.value = arr;
};
// 1-2获取该部门下所有成员
const getisUserAll = data => {
  data.forEach(elem => {
    elem.deptPersonChildren;
    isUserAll.value = [...isUserAll.value, ...elem.deptPersonChildren];
    if (elem.children?.length) {
      // if (elem.children.length) {
      // getDeptUserListAll(elem.children);
      getisUserAll(elem.children);
      // }
    }
  });
};
// 1-3 成员搜索
const onSearch = () => {
  if (userName.value) {
    isSearch.value = true;
    let list = [];
    isUserAll.value.forEach(elem => {
      let arr = elem.realName.match(userName.value);
      if (arr !== null) {
        deptStructureCopy.value.deptPersonChildren.forEach(v => {
          // v.deptName = '通讯录';
          if (v.userId === elem.userId) elem.deptName = v.deptName;
        });
        if (deptStructureCopy.value.children) {
          getUserDept(deptStructureCopy.value.children, elem);
        }
        list.push(elem);
      }
    });
    list = deduplication(list);
    deptStructure.value = {
      children: [],
      isTrue: false,
      deptPersonChildren: list
    };
    isDeptShow();
  } else {
    isSearch.value = false;
    // 搜索结束之后 肯定只有一个通讯录传一个true，跳过这个判断长度等于1的判断，可以继续执行depList内代码块
    depList(deptName.value[0], 1, true);
  }
};
// 1-4查找该人员所在部门
const getUserDept = (dept, user, deptName) => {
  dept.forEach(v => {
    v.deptPersonChildren.forEach(x => {
      x.deptName = deptName ? `${deptName}-${v.deptName}` : v.deptName;
      if (x.userId === user.userId) user.deptName = x.deptName;
    });
    if (v.children) {
      let name = deptName ? `${deptName}-${v.deptName}` : v.deptName;
      getUserDept(v.children, user, name);
    }
  });
};
// 1-5保留数组对象中非重复数据
const deduplication = arr => {
  let idList = [...new Set(arr.map(x => x.userId))];
  let arrList = [];
  idList.forEach(elem => {
    arrList.push(arr.find(x => x.userId === elem));
  });
  return arrList;
};
function onAddDevice() {
  // 增加设备接口
  let params = {
    locationId: locationId.value, // 位置id
    classId: classId.value, // 班级id
    deviceName: equipmentName.value.replace(/\s+/g, ''), // 设备名称
    onlineStatus: formDevices.infoState, // 在线状态
    // applicationName: '信息发布'
    applicationId: '2'
  };
  getDeviceListEast(params)
    .then(res => {
      addModelList.value = res.data.data; // 设备列表数据
      // 组装选择设备的数据
      let datas = [];
      res.data.data.forEach(elem => {
        let arr = [];
        elem.data.forEach(item => {
          let moduleVOList = [];
          // eslint-disable-next-line max-nested-callbacks
          item.moduleVOList.forEach(el => {
            moduleVOList.push({
              isTrue: false,
              configIds: el.configIds,
              funcModule: el.configId,
              equipmentId: item.deviceId,
              funcModuleName: el.configName
            });
          });
          // 设备id
          let deviceTrue = false;
          if (selectDeviceId.value.indexOf(item.deviceId) !== -1) {
            deviceTrue = true;
          }
          arr.push({
            isTrue: deviceTrue,
            clazzId: item.clazzId,
            clazzName: item.clazzName,
            deviceId: item.deviceId,
            deviceName: item.deviceName,
            locationId: item.locationId,
            locationName: item.locationName,
            modelId: item.modelId,
            modelName: item.modelName,
            onlineStatus: item.onlineStatus,
            funcModules: moduleVOList
          });
        });
        // 设备类型id;
        let isTrue = false;
        if (selectModelId.value.indexOf(elem.modelId) !== -1) {
          isTrue = true;
        }
        datas.push({
          deviceTypeId: elem.deviceTypeId,
          modelId: elem.modelId,
          positionType: elem.name,
          isTrue: isTrue,
          releaseInfoPositionVOS: arr
        });
      });
      selectionList.value = datas; // 组装后选择设备的数据
      // 处理搜索后取消设备时，类型的状态
      selectionList.value.forEach(v => {
        let oldNum = v.releaseInfoPositionVOS.length;
        let newNum = v.releaseInfoPositionVOS.filter(x => x.isTrue).length;
        if (oldNum === newNum) {
          v.isTrue = true;
        } else {
          v.isTrue = false;
        }
      });
    })
    .catch(() => {});
  if (params.deviceName !== '') {
    activeKey.value = ['0']; // 保持展开状态
  } else {
    activeKey.value = [];
  }
}

// 1.权限管理事件
function authorityManagement() {
  onAddDevice();
  // 组织架构接口
  deptName.value = [];
  getAllDeptInfo({ applicationId: store.state.user.appId }).then(res => {
    if (res.data.code === 200) {
      let arr = ref([]);
      res.data.data.forEach(item => {
        let arr2 = [];
        item.deptPersonChildren.forEach(elme => {
          arr2.push({
            isTrue: false,
            avatar: elme.avatar,
            id: elme.id,
            mobile: elme.mobile,
            realName: elme.realName,
            userId: elme.userId
          });
        });
        arr.value.push({
          isTrue: false,
          children: item.children,
          deptName: item.deptName,
          deptPersonChildren: arr2,
          id: item.id,
          level: item.level,
          parentId: item.parentId
        });
        // res.data.data = arr;
      });
      deptStructure.value = {
        children: arr.value,
        deptName: '通讯录',
        isTrue: false,
        deptPersonChildren: []
      };
      deptName.value.push(deptStructure.value);
      deptStructureCopy.value = JSON.parse(JSON.stringify(deptStructure.value));
      deptNumTotal(deptStructure.value);
      getDeptNumTotal(deptStructure.value);
    }
  });
  power.visible = true;
}
// 2.计算部门总人数
const deptNumTotal = data => {
  userAmount.value = [...data.deptPersonChildren];
  getDeptUserListAll(data.children);
  userAmount.value = deduplicationArr(data.deptPersonChildren, 'userId');
};
// 3.获取该部门下所有成员
const getDeptUserListAll = data => {
  if (data) {
    data.forEach(elem => {
      userAmount.value = [...userAmount.value, ...elem.deptPersonChildren];
      if (elem.children?.length) {
        getDeptUserListAll(elem.children);
      }
    });
  }
};
// 4.点击标题
const depList = (data, index, type) => {
  // 如果没有数据就不执行
  if (!data) return false;
  // 如果我判断导航栏只有一条的时候不继续执行，防止这里只有一个通讯录 的时候 用户一直点击通讯录
  if (deptName.value.length === 1 && !type) return false;
  // 让里面被选中的状态变为fasle
  selectedCheckedAll.value = false;
  // ??
  userName.value = undefined;
  deptStructure.value = data;
  deptName.value.push(data);
  isDeptShow();
  deptName.value.splice(index);
  // 全选搜索后取消当前人员，取消分组勾选状态
  let isTrueNum = [];
  let userIds = rightDeviceList.value.map(v => v.userId);
  data.children?.forEach(v => {
    deptNumTotal(v);
    let selectUser = [];
    userAmount.value.forEach(x => {
      if (userIds.indexOf(x.userId) !== -1) selectUser.push(x);
    });
    if (v.isTrue) {
      isTrueNum++;
      v.isTrue = true;
      if (selectStudentValue.value.indexOf(v.id) === -1) selectStudentValue.value.push(v.id);
    } else {
      // 选中人数和当前部门人数相当并且当前部门人数不能小于0
      if (selectUser.length === userAmount.value.length && userAmount.value.length > 0) {
        v.isTrue = true;
        if (selectStudentValue.value.indexOf(v.id) === -1) {
          v.isTrue = true;
          selectStudentValue.value.push(v.id);
        }
      }
    }
  });
  data.deptPersonChildren?.forEach(v => {
    if (v.isTrue) {
      isTrueNum++;
    }
  });
  let deptPersonChildrenNum = data.deptPersonChildren?.length || 0;
  let childrenNum = data.children?.length || 0;
  let chiderLength = deptPersonChildrenNum + childrenNum;
  data.isTrue = isTrueNum > 0 && isTrueNum === chiderLength;
  // 删除面包屑
  deptName.value.splice(index);
};
// 全选和单选重组数据的方法
function assemble(data, userList) {
  // console.log(1111, userList);

  let availableList = [];
  let arr = [];
  // if (data.length === 0) {
  // quanCheked.value = false;
  // }
  // let quanchengList = [];
  data.forEach(item => {
    // quanchengList.push(item.equipmentTypeId * 1 === 999 ? 999 : 888);
    // if (item.equipmentTypeId * 1 === 999) {
    //   console.log(11111111111111);
    //   quanCheked.value = true;
    // }
    if (item.equipmentTypeId * 1 !== 999) {
      // console.log(222222);
      arr.push(...item.schControlledEquipmentBOS);
      let releaseInfoPositionVOS = [];
      item.schControlledEquipmentBOS.forEach(elem => {
        let funcModules = [];
        elem.equipmentPowers.forEach(el => {
          funcModules.push({
            configIds: el.configIds,
            equipmentId: el.equipmentId,
            funcModule: el.componentId,
            funcModuleName: el.componentName,
            isTrue: true
          });
        });
        releaseInfoPositionVOS.push({
          isTrue: false,
          clazzId: elem.clazzId,
          clazzName: elem.belongClass,
          deviceId: elem.equipmentId,
          deviceName: elem.equipmentName,
          locationId: elem.locationId,
          locationName: elem.equipmentPosition,
          deviceTypeId: elem.equipmentTypeId,
          modelName: elem.equipmentTypeName,
          funcModules: funcModules
        });
        // availableList.push({
        //   modelId: item.modelId,
        //   controllerUserId: elem.controllerUserId,
        //   positionType: item.equipmentTypeName,
        //   releaseInfoPositionVOS: releaseInfoPositionVOS
        // });
      });
      availableList.push({
        deviceTypeId: item.equipmentTypeId,
        controllerUserId: item.schControlledEquipmentBOS[0].controllerUserId,
        positionType: item.equipmentTypeName,
        releaseInfoPositionVOS: releaseInfoPositionVOS
      });
    } else {
      availableList.push({
        deviceTypeId: 999,
        controllerUserId: '',
        positionType: '',
        releaseInfoPositionVOS: []
      });
    }
  });
  // console.log(88888888, quanchengList);
  // 如果是2就执行多选
  if (userList === 2) {
    // 可用设备列表rightDeviceList
    rightDeviceList.value.forEach(v => {
      // availableList后台返的数据，如果id和页面渲染的id一致时，就对应id给这个人push后台相应的数据
      availableList.forEach(x => {
        if (x.controllerUserId === v.userId) v.availableList.push(x);
      });
    });
  } else {
    rightDeviceList.value.forEach(item => {
      if (item.userId === userList.userId) item.availableList = availableList;
    });
  }
}
// 已选中的人
const onRealNameChecked = (e, userList) => {
  userList.isTrue = e.target.checked;
  // 判断人员全部选中为全选
  let checkedTrue = [];
  deptStructure.value.deptPersonChildren.forEach(item => {
    checkedTrue.push(item.isTrue);
  });
  if (checkedTrue.indexOf(false) !== -1) {
    selectedChecked.value = false;
  } else {
    selectedChecked.value = true;
  }
  // 根据id查询所含设备接口
  if (e.target.checked) {
    // 给部门赋值
    let deptNameA = deptStructure.value.deptName; // 点击部门时用这个值
    if (deptStructure.value.deptName === undefined) {
      deptNameA = userList.deptName; // 搜索时赋值
    }
    // 组装数据push到右侧
    let obj = {
      userId: userList.userId,
      realName: userList.realName,
      controllerUserPhone: userList.mobile,
      controllerUserDeptName: deptNameA,
      availableList: []
    };
    rightDeviceList.value.push(obj);
    // console.log(333, checkedTrue);
    availableEquipment([userList.userId]).then(res => {
      assemble(res.data.data, userList);
      getQuanChengApplication(rightDeviceList.value, checkedTrue); // 处理泉城e学应用选中状态
    });
  } else {
    // console.log(222, checkedTrue);
    rightDeviceList.value = rightDeviceList.value.filter(elem => elem.userId !== userList.userId);
    getQuanChengApplication(rightDeviceList.value, checkedTrue); // 处理泉城e学应用选中状态
  }
  // console.log('设备', rightDeviceList.value);
  let isTrueNum = 0;
  deptStructure.value.deptPersonChildren?.forEach(item => {
    if (item.isTrue) {
      isTrueNum++;
    }
  });
  deptStructure.value.children?.forEach(item => {
    if (item.isTrue) {
      isTrueNum++;
    }
  });
  let deptPersonChildrenNum = deptStructure.value.deptPersonChildren?.length || 0;
  let childrenNum = deptStructure.value.children?.length || 0;
  let chiderLength = deptPersonChildrenNum + childrenNum;
  deptStructure.value.isTrue = isTrueNum > 0 && isTrueNum === chiderLength;
};
function getQuanChengApplication(data, userList) {
  console.log('fangf', data, userList); //
  if (data.length === 0) {
    // 没有选中人 肯定不被选中
    quanCheked.value = false;
  } else {
    let quanchengList = [];
    data.forEach(item => {
      if (item.availableList.length === 0) {
        quanchengList.push(888);
      } else {
        item.availableList.forEach(it => {
          quanchengList.push(it.deviceTypeId);
        });
      }
    });
    // console.log(quanchengList); // 每个人身上的id =999(泉城e学)的数量跟选中人的数量一样 代表每个人都是泉城e学
    let arr = quanchengList.filter(item => item * 1 === 999);
    let userCheckedList = userList.filter(item => item);
    console.log(arr);
    console.log(userCheckedList);
    if (arr.length === userCheckedList.length) {
      quanCheked.value = true;
    } else {
      quanCheked.value = false;
    }
  }
}
// 5.全选
const onCheckAllChange = e => {
  // 计算部门总人数
  deptNumTotal(deptStructure.value);
  // 获取所有人员
  userListAll.value = [];
  userListAll.value = [...userListAll.value, ...deptStructure.value.deptPersonChildren];
  // 获取当前部门下所有成员
  getDeptListArr(deptStructure.value.children);
  if (e.target.checked) {
    // 为true所有部门状态为true
    if (deptStructure.value.children !== undefined) {
      deptStructure.value.children.forEach(elme => {
        elme.isTrue = true;
        deptNameId.value.push(elme.id);
      });
    }
    if (deptStructure.value.deptPersonChildren !== undefined) {
      deptStructure.value.deptPersonChildren.forEach(elme => {
        elme.isTrue = true;
        deptNameId.value.push(elme.id);
      });
    }
    let userId = [];
    // 将所有人员push到设备列表和userId传给后台
    let realName = [];
    let userIds = rightDeviceList.value.map(v => v.userId);
    userListAll.value.forEach(item => {
      // 右侧列表不存在用户id时再push用户id,避免重调接口设备重复
      if (userIds.indexOf(item.userId) === -1) {
        userId.push(item.userId);
      }
      realName.push({ realName: item.realName, userId: item.userId, availableList: [] });
    });
    implementCheckedAll();
    // 改变选中的所有状态
    ergodicIsChar(deptStructure.value, true);
    // 判断人员全部选中为全选
    let checkedTrue = [];
    deptStructure.value.deptPersonChildren.forEach(item => {
      checkedTrue.push(item.isTrue);
    });
    // 请求接口
    let setUserId = [...new Set(userId)];
    if (setUserId.length) {
      availableEquipment(setUserId).then(res => {
        assemble(res.data.data, 2);
        getQuanChengApplication(rightDeviceList.value, checkedTrue); // 处理泉城e学应用选中状态
      });
    }
  } else {
    if (deptStructure.value.children !== undefined) {
      deptStructure.value.children.forEach(elme => {
        elme.isTrue = false;
        if (deptNameId.value.indexOf(elme.id) > -1) {
          deptNameId.value.splice(deptNameId.value.indexOf(elme.id), 1);
        }
        if (selectStudentValue.value.indexOf(elme.id) > -1) {
          selectStudentValue.value.splice(selectStudentValue.value.indexOf(elme.id), 1);
        }
        // eslint-disable-next-line prettier/prettier
        let target = { checked: false };
        onDeptNameChecked({ target }, elme, elme.deptPersonChildren);
      });
    }
    if (deptStructure.value.deptPersonChildren !== undefined) {
      deptStructure.value.deptPersonChildren.forEach(elme => {
        elme.isTrue = false;
        if (deptNameId.value.indexOf(elme.id) > -1) {
          deptNameId.value.splice(deptNameId.value.indexOf(elme.id), 1);
        }
        if (selectStudentValue.value.indexOf(elme.userId) > -1) {
          selectStudentValue.value.splice(selectStudentValue.value.indexOf(elme.userId), 1);
        }
        // eslint-disable-next-line prettier/prettier
        let target = { checked: false };
        onRealNameChecked({ target }, elme);
      });
    }
    // 改变选中的所有状态
    ergodicIsChar(deptStructure.value, false);
    quanCheked.value = false; // 全部不勾选, 泉城e学一定是false
  }
};
// 全选改变状态
function ergodicIsChar(arr, type) {
  console.log(arr, type, 9999);
  arr.isTrue = type;
  if (arr.children?.length) {
    arr.children.forEach(item => {
      ergodicIsChar(item, type);
    });
  }
  if (arr.deptPersonChildren?.length) {
    arr.deptPersonChildren.forEach(item => {
      item.isTrue = type;
    });
  }
  // })
}
// 7.全选循环搜索成员执行方法
const implementCheckedAll = () => {
  deptStructure.value.deptPersonChildren.forEach(elem => {
    let arr = rightDeviceList.value.map(x => x.userId);
    if (arr.indexOf(elem.userId) === -1) {
      let obj = {
        userId: elem.userId,
        realName: elem.realName,
        controllerUserPhone: elem.mobile,
        controllerUserDeptName: deptStructure.value.deptName,
        id: deptStructure.value.id,
        availableList: []
      };
      rightDeviceList.value.push(obj);
      if (selectStudentValue.value.indexOf(elem.userId) === -1) {
        selectStudentValue.value.push(elem.userId);
      }
    }
  });
  if (deptStructure.value.children?.length) {
    // if (deptStructure.value.children.length) {
    let selectTotalList = [];
    deptStructure.value.children?.forEach(elem => {
      elem.isTrue = true; // 让选中的分组状态变成true
      selectTotalList = rightDeviceList.value.map(x => x.userId);
      elem.deptPersonChildren.forEach(x => {
        if (selectTotalList.indexOf(x.userId) === -1) {
          // 全选后的右侧数据
          rightDeviceList.value.push({
            userId: x.userId,
            realName: x.realName,
            controllerUserPhone: x.mobile,
            controllerUserDeptName: elem.deptName,
            id: elem.id,
            availableList: []
          });
        }
      });
      if (selectStudentValue.value.indexOf(elem.id) === -1) selectStudentValue.value.push(elem.id);
      if (elem.children?.length) {
        // if (elem.children.length) {
        isDeptCheckedAll(elem.children, elem, selectTotalList);
        // }
      }
    });
    // }
  }
  selectStudentValue.value = [...new Set(selectStudentValue.value)];
};
// 8.部门全选
const isDeptCheckedAll = (data, elem, arr) => {
  data.forEach(v => {
    arr = rightDeviceList.value.map(x => x.userId);
    v.deptPersonChildren.forEach(x => {
      if (arr.indexOf(x.userId) === -1) {
        rightDeviceList.value.push({
          userId: x.userId,
          realName: x.realName,
          controllerUserPhone: x.mobile,
          controllerUserDeptName: elem.deptName,
          id: elem.id,
          availableList: []
        });
        if (selectStudentValue.value.indexOf(elem.id) === -1) {
          selectStudentValue.value.push(elem.id);
        }
      }
    });
    if (v.children?.length) {
      // if (v.children.length) {
      isDeptCheckedAll(v.children, elem, arr);
      // }
    }
  });
};
// 9.点击部门
function onDeptName(item, data) {
  if (!item.isTrue) {
    deptNameId.value = deptNameId.value.filter(elem => elem !== item.id);
  }
  deptStructure.value = item;
  deptName.value.push(item);
  isDeptShow();
}
let deptNameId = ref([]);
// 10. 勾选部门
const onDeptNameChecked = (e, data, deptPersonChildren) => {
  data.isTrue = e.target.checked;
  // 获取所有人员
  userListAll.value = [];
  userListAll.value = [...userListAll.value, ...data.deptPersonChildren];
  // 当下部门所有人员
  getDeptListArr(data.children);
  if (e.target.checked) {
    deptNameId.value.push(data.id); // 部门id
    userListAll.value.forEach(elem => {
      let arr = rightDeviceList.value.map(x => x.userId);
      if (arr.indexOf(elem.userId) === -1) {
        rightDeviceList.value.push(elem);
      }
    });
    // 勾选部门往右侧push数据
    let realName = [];
    let userId = [];
    // 合并数组拿到号码
    let mobile = [...new Set([...rightDeviceList.value, ...deptPersonChildren])];
    let rightList = JSON.parse(JSON.stringify(mobile));
    rightList.forEach(item => {
      realName.push({
        realName: item.realName,
        userId: item.userId,
        controllerUserDeptName: data.deptName,
        controllerUserPhone: item.mobile,
        availableList: []
      });
      userId.push(item.userId);
    });
    // rightDeviceList.value = realName;
    rightDeviceList.value = deduplicationArr(realName, 'userId');
    // 去重人员id
    let setUserId = [...new Set(userId)];
    // 已选人员id传给后台
    if (setUserId.length !== 0) {
      availableEquipment(setUserId).then(res => {
        assemble(res.data.data, 2);
      });
    }

    // 改变选中的所有状态
    ergodicIsChar(data, true);
  } else {
    deptNameId.value = deptNameId.value.filter(elem => elem !== data.id);
    let arr = userListAll.value.map(x => x.userId);
    let selectTotalCopy = [];
    rightDeviceList.value.forEach(elem => {
      if (arr.indexOf(elem.userId) === -1) selectTotalCopy.push(elem);
    });
    rightDeviceList.value = selectTotalCopy;
    data.deptPersonChildren?.forEach(item => {
      item.isTrue = false;
    });
    data.children?.forEach(item => {
      item.isTrue = false;
    });
    console.log(1111);
    ergodicIsChar(data, false);
  }
  let isTrueNum = 0;
  deptStructure.value.children?.forEach(item => {
    if (item.isTrue) {
      isTrueNum++;
    }
  });
  deptStructure.value.deptPersonChildren?.forEach(item => {
    if (item.isTrue) {
      isTrueNum++;
    }
  });
  let deptPersonChildrenNum = deptStructure.value.deptPersonChildren?.length || 0;
  let childrenNum = deptStructure.value.children?.length || 0;
  let chiderLength = deptPersonChildrenNum + childrenNum;
  deptStructure.value.isTrue = isTrueNum > 0 && isTrueNum === chiderLength;
};

// 11. 递归获取当前部门下所有成员
const getDeptListArr = data => {
  if (data !== undefined) {
    data.forEach(k => {
      userListAll.value = [...userListAll.value, ...k.deptPersonChildren];
      if (k.children !== undefined) {
        if (k.children.length) {
          getDeptListArr(k.children);
        }
      }
    });
  }
};
const selectLength = computed(() => {
  let num = 0;
  let list = selectDevice.value.map(x => x.releaseInfoPositionVOS.length);
  list.forEach(v => {
    num += Number(v);
  });
  return num;
});

// 12.回显
function isDeptShow() {
  userListAll.value = [];
  let arr = rightDeviceList.value.map(x => x.userId);
  deptStructure.value.deptPersonChildren.forEach(k => {
    if (arr.indexOf(k.userId) !== -1) {
      if (selectStudentValue.value.indexOf(k.userId) === -1) {
        selectStudentValue.value.push(k.userId);
      }
    }
  });
  if (deptStructure.value.children?.length) {
    let userIds = rightDeviceList.value.map(v => v.userId);
    deptStructure.value.children?.forEach((elem, index) => {
      let indexOfNum = 0;
      let selectUser = []; // 临时部门人员
      deptNumTotal(elem); // 当前部门人员
      userAmount.value.forEach(x => {
        if (userIds.indexOf(x.userId) !== -1) selectUser.push(x);
      });
      if (selectUser.length === userAmount.value.length && userAmount.value.length > 0) {
        if (selectStudentValue.value.indexOf(elem.id) === -1) {
          selectStudentValue.value.push(elem.id);
        }
      }
      elem.deptPersonChildren.forEach(x => {
        if (arr.indexOf(x.userId) !== -1) {
          indexOfNum++;
        }
      });

      if (elem.isTrue && selectStudentValue.value.indexOf(elem.id) === -1) {
        selectStudentValue.value.push(elem.id);
      }
      if (indexOfNum === elem.deptPersonChildren.length && indexOfNum > 0) {
        if (selectStudentValue.value.indexOf(elem.id) === -1) {
          selectStudentValue.value.push(elem.id);
        }
      }
    });
  }
  isDeptUser(deptStructure.value, deptStructure.value.children, arr);
}
// 13.递归回显
function isDeptUser(array, data, arr) {
  let isTrueNum = 0; // 声明一个变量选中就累加
  let childrenNum = array.children?.length || 0; // 部门长度
  let deptPersonChildrenNum = array.deptPersonChildren?.length || 0; // 人员长度
  let arrayNum = childrenNum + deptPersonChildrenNum; // 人员和部门长度
  data?.forEach(item => {
    if (item.isTrue) isTrueNum++;
    if (item.children?.length) {
      isDeptUser(item, item.children, arr);
    }
    if (item.deptPersonChildren?.length) {
      item.deptPersonChildren.forEach(elem => {
        if (arr.indexOf(elem.userId) === -1) {
          item.isTrue = false;
          let indexOf = selectStudentValue.value.indexOf(item.id);
          let elemIndexOf = selectStudentValue.value.indexOf(elem.userId);
          if (indexOf > -1) selectStudentValue.value.splice(indexOf, 1);
          if (elemIndexOf > -1) selectStudentValue.value.splice(elemIndexOf, 1);
        }
      });
    }
    if (!item.isTrue) {
      array.isTrue = false;
      let indexOf = selectStudentValue.value.indexOf(array.id);
      if (indexOf > -1) selectStudentValue.value.splice(indexOf, 1);
    }
  });
  array.deptPersonChildren?.forEach(elem => {
    if (elem.isTrue) isTrueNum++;
    if (arr.indexOf(elem.userId) === -1) {
      array.isTrue = false;
      let indexOf = selectStudentValue.value.indexOf(elem.userId);
      if (indexOf > -1) selectStudentValue.value.splice(indexOf, 1);
    }
  });
  if (!array.isTrue) {
    array.isTrue = false;
    let indexOf = selectStudentValue.value.indexOf(array.id);
    if (indexOf > -1) selectStudentValue.value.splice(indexOf, 1);
  }
  if (isTrueNum > 0 && isTrueNum === arrayNum) {
    if (selectStudentValue.value.indexOf(array.id) === -1) {
      array.isTrue = true;
      selectStudentValue.value.push(array.id);
    }
  }
}
/** ***********************已选人员完毕***********************/
function quanchengClick() {
  if (rightDeviceList.value.length === 0) {
    setTimeout(() => {
      quanCheked.value = false;
    }, 10);
    Message.warning('请先选择成员');

    return;
  } else {
    quanCheked.value = !quanCheked.value;
  }
}
const arrLength = ref([]);
// 增加设备弹窗
function onEquipments(e, data) {
  data.isTrue = e.target.checked;
  let availableList = [];
  rightDeviceList.value.forEach(el => {
    availableList.push(...el.availableList);
  });
  console.log(444, availableList);
  availableList = availableList.filter(item => item.deviceTypeId !== 999);
  let infoId = [];
  availableList.forEach(elem => {
    infoId = [...infoId, ...elem.releaseInfoPositionVOS.filter(v => v.isTrue)];
    arrLength.value = infoId;
  });
}
function removeOk() {
  let availableList = [];
  rightDeviceList.value.forEach(el => {
    availableList.push(...el.availableList);
  });
  availableList = availableList.filter(item => item.deviceTypeId !== 999);
  availableList.forEach((elem, index) => {
    if (elem.releaseInfoPositionVOS) {
      elem.releaseInfoPositionVOS.forEach(item => {
        if (item.isTrue) {
          // elem.releaseInfoPositionVOS.splice(0, arrLength.value.length);
          elem.releaseInfoPositionVOS = elem.releaseInfoPositionVOS.filter(v => !v.isTrue);
          // item.isTrue = false;
        }
      });
    }
  });
  rightDeviceList.value.forEach(el => {
    el.availableList = el.availableList.filter(v => v.releaseInfoPositionVOS.length);
  });
  remove.visible = false;
}
// 分页change事件
function onChange(params) {
  current.value = params;
}
// 重置
function resetForm() {
  classId.value = ''; // 班级id
  locationId.value = ''; // 位置id
  locationChoice.value = ''; // 位置数据
  locationTreeKeys.value = []; // 位置弹窗取消选中
  selectedKeys.value = []; // 班级弹窗取消选中
  choiceClass.value = ''; // 班级数据
  selectDormitoryRoomValue.value = []; // 班级弹窗取消选中
  equipmentName.value = ''; // 设备名称
  formDevices.infoState = ''; // 设备状态
  controllerUserName.value = ''; // 使用者
  getData();
  deviceslist.value.onActiveKey([]);
}
const childRefSortlist = ref(null);
// 排序接口
function KeepSorting() {
  let equipmentSort = [];
  modelList.value.forEach((item, index) => {
    equipmentSort.push({
      equipmentTypeId: item.deviceTypeId,
      equipmentTypeName: item.name,
      sort: index
    });
  });
  saveEquipmentSort({ equipmentSort }).then(() => {});
  childRefSortlist.value.KeepSorting();
  state.value = 0;
}
// 保存排序
function getSortlistData(data) {
  // modelLists.value = data;
}
// 取消排序
function unsortData(data) {
  modelList.value = data;
}
function searchDevice() {
  getData();
  deviceslist.value.onActiveKey(['0']);
}
// 获取设备
let deviceslist = ref(null);
function getData() {
  setTimeout(() => {
    deviceslist.value.loadings(true);
  });
  let params = {
    identity: localStorage.getItem('identity'),
    // identity: 8,
    controllerUserName: controllerUserName.value.replace(/\s+/g, ''),
    locationIds: locationId.value, // 位置id
    classIds: classId.value, // 班级id
    deviceName: controllerUserName.value.replace(/\s+/g, ''), // 设备名称
    onlineStatus: formDevices.infoState // 在线状态
  };
  getDeviceListCompetence(params)
    .then(res => {
      let data = [];
      res.data.data.forEach(item => {
        data.push({
          checked: false,
          ...item
        });
      });
      modelList.value = data;
      setTimeout(() => {
        deviceslist.value.loadings(false);
      });
    })
    .catch(() => {
      setTimeout(() => {
        deviceslist.value.loadings(false);
      });
    });
}

// 取消和确定事件
function removeCancel() {
  remove.visible = false;
}
// 设备列表单个移除
function removeOne(data, ites) {
  console.log(rightDeviceList.value);
  rightDeviceList.value.forEach(itemAll => {
    itemAll.availableList.forEach((elem, avIndex) => {
      if (elem.deviceTypeId !== 999) {
        if (itemAll.userId === ites.userId) {
          elem.releaseInfoPositionVOS = elem.releaseInfoPositionVOS.filter(
            v => v.deviceId !== data.deviceId
          );
        }
      }
    });
    // 当前设备数组wei空时,移除自己本身
    itemAll.availableList = itemAll.availableList.filter(v => v.releaseInfoPositionVOS.length);
  });
}
// 位置树
let locationId = ref(''); // 位置Id
function onSelect(selectedKeys, info) {
  locationId.value = selectedKeys.join(',');
  locationChoice.value = info.node.name;
}
function onExpandLocation(expandedKeys) {
  locationexpandedKeys.value = expandedKeys;
}
// 增加设备 取消事件
function addCancel() {
  addDevice.visible = false;
  power.visible = true;
  selectedClose(); // 清除已选择弹窗内容
  onEquipmentSearch();
}
const editList = ref([]);
// 修改弹窗事件
function onModify(index) {
  indexs.value = index;
  // event.stopPropagation();
  modify.visible = true;
  editList.value = rightDeviceList.value[index];

  editList.value.availableList = editList.value.availableList.filter(
    ite => ite.deviceTypeId * 1 !== 999
  );

  console.log(editList.value);
  power.visible = false;
  // editList.value.push(rightDeviceList.value[index]);
}
// // 修改弹窗事件
// function onModify(event) {
//   event.stopPropagation();
//   modify.visible = true;
// }
// 修改弹窗 取消事件
function modifyCancel() {
  modify.visible = false;
  power.visible = true;
}

// 权限管理-所在-所属- 取消事件
function dialogCancel() {
  rightDeviceList.value = [];
  quanCheked.value = false;
  selectedCheckedAll.value = false;
  deptStructure.value = [];
  power.visible = false;
  deptName.value = [];
  userName.value = '';
  selectedChecked.value = false;
  selectStudentValue.value = []; // 清空已选中的人员
  onSearch();
}

// 1-4保留数组对象中非重复数据
const deduplicationArr = (arr, id) => {
  let idList = [...new Set(arr.map(x => x[id]))];
  let arrList = [];
  idList.forEach(elem => {
    arrList.push(arr.find(x => x[id] === elem));
  });
  return arrList;
};

function dialogOk() {
  let params = [];
  if (quanCheked.value) {
    rightDeviceList.value.forEach(item => {
      item.availableList.push({
        deviceTypeId: '999',
        modelId: '305021465919496192',
        positionType: '宿舍标牌',
        releaseInfoPositionVOS: [
          {
            clazzId: '',
            clazzName: '',
            deviceId: '999',
            deviceName: '泉城e学',
            locationId: '400719133349511168',
            locationName: '',
            modelId: '305021465919496192',
            modelName: '泉城e学',
            funcModules: []
          }
        ]
      });
    });
  }
  console.log('hfgjdh ', rightDeviceList.value);
  let selectDeviceList = []; // 每个添加人身上设备的长度
  rightDeviceList.value.forEach(item => {
    let schControlled = [];
    selectDeviceList.push(item.availableList.length);
    item.availableList.forEach(elem => {
      elem?.releaseInfoPositionVOS.forEach(v => {
        let equipmentPowerBOS = [];
        // eslint-disable-next-line max-nested-callbacks
        v.funcModules.forEach(x => {
          equipmentPowerBOS.push({
            configIds: x.configIds, // 新增加的configIds
            funcModule: x.funcModule, //   控制设备功能的组件ID
            equipmentId: x.equipmentId, // 可控制设备ID
            funcModuleName: x.funcModuleName //    控制设备功能的组件名称
          });
        });
        schControlled.push({
          controllerUserPhone: item.controllerUserPhone, // 控制设备的人员手机号
          controllerUserDeptName: item.controllerUserDeptName, // 控制设备的人员部门名称
          equipmentId: v.deviceId, //  可控制设备ID
          equipmentTypeId: elem.deviceTypeId, //   控制设备类型ID
          equipmentTypeName: v.modelName, //    设备类型名称
          equipmentName: v.deviceName, //    设备名称
          equipmentPosition: v.locationName, //   设备位置
          belongClass: v.clazzName, //    所属班级
          equipmentPowerBOS: equipmentPowerBOS
        });
      });
    });
    params.push({
      controllerUserId: item.userId, // 控制设备的人员ID
      controllerUserName: item.realName, // 控制设备的人员名称
      schControlledEquipmentBOS: deduplicationArr(schControlled, 'equipmentId')
    });
  });
  if (rightDeviceList.value.length !== 0) {
    // console.log(selectDeviceList.every(item => item === 0));
    // if (selectDeviceList.every(item => item === 0)) {
    //   Message.warning('请添加设备后再保存！');
    //   return;
    // console.log(3333, deduplicationArr(params, 'controllerUserId'));
    saveEquipment(deduplicationArr(params, 'controllerUserId')).then(res => {
      if (res.data.code === 200) {
        Message.success('设备添加成功');
      }
    });
  }
  power.visible = false;
  selectedChecked.value = false; // 关闭部门下的全选
  rightDeviceList.value = []; // 清空右侧数据
  deptName.value = []; // 清空面包屑
  deptStructure.value = []; // 清空部门
  selectedCheckedAll.value = false; // 关闭部门的全选
  selectStudentValue.value = []; // 清空已选中的人员
  userName.value = ''; // 清空搜索的字段
  onSearch();
  activeKeys.value = 2; // 选中设备tabs
  quanCheked.value = false; // 清空泉城e学选中
}
// 切换列表数据
function onSwitch(e) {
  if (e === 0) {
    localStorage.setItem('modelList', JSON.stringify(modelList.value));
    state.value = 1;
  } else {
    childRefSortlist.value.unsort();
    state.value = 0;
  }
}

// 筛选条件所在位置改变
function onLocationIdsChange(vals) {
  let selectedKeys = vals.map(item => item[item.length - 1]);
  locationId.value = selectedKeys.join(',');
  searchDevice();
}
// 筛选条件所属班级改变
function onClassIdsChange(vals, options) {
  // 只返回选中班级id
  let selectedKeys = options
    .map(item => {
      let selectedOption = item[item.length - 1];
      return getLastClassId(selectedOption);
    })
    .flat(Infinity);
  classId.value = selectedKeys.join(',');
  searchDevice();
}
// 递归取最后一级班级id
function getLastClassId(selectedOption) {
  if (selectedOption.children?.length > 0) {
    return selectedOption.children.map(childItem => {
      return childItem.children?.length > 0 ? getLastClassId(childItem) : childItem.value;
    });
  }
  return selectedOption.value;
}
// 筛选条件设备状态改变
function onStateChange(e, val) {
  formDevices.infoState = val?.value ?? '';
  searchDevice();
}
</script>
<style lang="less" scoped>
.power-btn {
  padding: 0 !important;
  width: 80px !important;
  height: 24px !important;
  // background-color: #d6aa56;
  color: var(--themecolor);
  border: 1px solid var(--themecolor);
  /deep/ .micro-ant-btn:hover {
    color: #ffffff !important;
    border-color: #fe8f8f !important;
    border: none !important;
  }
}
.add-btsn {
  padding: 0 !important;
  width: 80px !important;
  height: 24px !important;
}
/deep/ .micro-ant-select-item-option-selected {
  background: var(--themecolor) !important;
  color: #ffffff !important;
}
.micro-ant-tree-treenode-checkbox-checked {
  background: var(--themecolor5);
  width: 100%;
}
/deep/.power-btn:hover {
  color: #ffffff !important;
}
.power-btn:hover {
  color: var(--themecolor5) !important;
}
@import './index.less';
</style>
